package deadletterexchange;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import utils.RabbitMQUtil;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

// 死信队列学习 - 消费者
public class Consumer01 {

    // 普通交换机名称
    public static final String NORMAL_EXCHANGE_NAME = "normal_exchange";
    // 死信交换机名称
    private static final String DEAD_EXCHANGE_NAME = "dead_exchange";

    // 声明死信队列名称
    public static final String DEAD_QUEUE_NAME = "dead-queue";
    // 声明正常队列名称
    public static final String NORMAL_QUEUE_NAME = "normal-queue";

    public static void main(String[] args) throws IOException, TimeoutException {
        
        Channel channel = RabbitMQUtil.getChannel();
        //声明死信和普通交换机 类型为direct
        channel.exchangeDeclare(NORMAL_EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(DEAD_EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
        //死信队列绑定死信交换机与routingkey
        channel.queueDeclare(DEAD_QUEUE_NAME, false, false, false, null);
        channel.queueBind(DEAD_QUEUE_NAME, DEAD_EXCHANGE_NAME, "lisi");
        
        // 正常队列绑定死信队列信息
        Map<String,Object> params = new HashMap<>();
        //正常队列设置死信交换机 参数key是固定值
        params.put("x-dead-letter-exchange", DEAD_EXCHANGE_NAME);
        //正常队列设置死信routing-key 参数key是固定值
        params.put("x-dead-letter-routing-key", "lisi");
        //params.put("x-max-length", 6);
        
        channel.queueDeclare(NORMAL_QUEUE_NAME, false, false, false, params);
        channel.queueBind(NORMAL_QUEUE_NAME, NORMAL_EXCHANGE_NAME, "zhangsan");

        System.out.println("等待接收消息...");
        DeliverCallback deliverCallback = (consumerTag,deliver) ->{
            String message = new String(deliver.getBody(), StandardCharsets.UTF_8);
            if(message.equals("info5")){
                System.out.println("消息 "+message+"是被C1拒接接受的");
                channel.basicReject(deliver.getEnvelope().getDeliveryTag(),false);
            }else {
                System.out.println("Consumer01接收到消息："+message);
                channel.basicAck(deliver.getEnvelope().getDeliveryTag(), false);
            }
        };
        // 消费消息（开启手动应答）
        channel.basicConsume(NORMAL_QUEUE_NAME, false, deliverCallback,consumerTag -> {});
    }
    
}
